package com.marver.common.handler;

import com.marver.common.exception.HmException;
import com.marver.common.result.Msg;
import com.marver.common.result.Result;
import com.marver.common.result.ResultStatus;
import com.marver.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.TypeMismatchException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局异常处理
 * ResponseEntityExceptionHandler
 * @Author: wangxc
 * @GitHub: https://github.com/vector4wang
 * @CSDN: http://blog.csdn.net/qqhjqs?viewmode=contents
 * @BLOG: http://vector4wang.tk
 * @wxid: BMHJQS
 * 参考:http://neverflyaway.iteye.com/blog/2301571  http://blog.csdn.net/u010935920/article/details/71024018
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    /**
     * 系统异常处理，比如：404,500
     * @param req
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result defaultErrorHandler(HttpServletResponse resp,HttpServletRequest req, Exception e) throws Exception {
        logger.error("", e);
        Result baseResp = null;
        Msg msg = new Msg();
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            msg.setTip(ResultStatus.getMsg(ResultStatus.http_status_not_found.getErrorCode()));
            msg.setStack(getStackMsg(e));
        	baseResp=new Result(ResultStatus.http_status_not_found.getErrorCode(),msg);
        }if (e instanceof HttpRequestMethodNotSupportedException) {
            msg.setTip("请求方式不支持");
            msg.setStack(getStackMsg(e));
        	baseResp=new Result(ResultStatus.http_status_internal_server_error.getErrorCode(),msg);
        }if(e instanceof TypeMismatchException){
            msg.setTip("参数类型转换错误");
            msg.setStack(e.getMessage());
        	baseResp=new Result(ResultStatus.INVALID_PARAM.getErrorCode(),msg);
        }if(e instanceof HmException){
            msg.setTip(e.getMessage());
            baseResp=new Result(((HmException) e).getCode(),msg);
        } else{
            msg.setTip("系统错误，请稍后重试");
            msg.setStack(getStackMsg(e));
        	baseResp=new Result(ResultStatus.error_sys.getErrorCode(),msg);
        }
//        resp.setHeader("content-type", "application/json");
//        resp.setContentType("application/json");
//        resp.setHeader("Content-Disposition", "inline");
        return baseResp;
    }

    private static String getStackMsg(Exception e) {
        StringBuffer sb = new StringBuffer();
        StackTraceElement[] stackArray = e.getStackTrace();
        for (StackTraceElement element : stackArray) {
            if(element.toString().indexOf("com.marver")!=-1) {
                sb.append(element.toString() + "\n");
            }
        }
        if(StringUtils.isEmpty(sb.toString())){
            return e.getMessage();
        }
        return sb.toString();
    }
}